package com.mf;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * ClassName: ${NAME}
 * Package: com.mf
 * Description:
 *
 * @Author: lmf
 * @Create: 2024/4/26 17:11
 * @Version: 1.0
 */
public class ConnectSocketMain {
    public static void main(String[] args) {
        int port = 12345; // 服务器监听的端口号

        try (
                // 创建 ServerSocket 来监听客户端连接
                ServerSocket serverSocket = new ServerSocket(port);
                // 接受客户端连接，创建 Socket 对象
                Socket clientSocket = serverSocket.accept();
                // 获取 Socket 的输入流和输出流
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
                // 创建 Scanner 来读取标准输入
                Scanner scanner = new Scanner(System.in)
        ) {
            System.out.println("客户端已连接。请输入要发送的消息（输入 'exit' 退出）：");

            // 循环读取终端输入，直到用户输入 'exit'
            while (scanner.hasNextLine()) {
                String userInput = scanner.nextLine();
                if ("exit".equalsIgnoreCase(userInput)) {
                    break; // 用户输入 'exit'，退出循环
                }

                // 向客户端发送字符串消息
                out.println("服务器发送: " + userInput);

//                // 读取并打印客户端的响应（可选）
//                String response = in.readLine();
//                if (response != null) {
//                    System.out.println("客户端响应: " + response);
//                }
            }

            System.out.println("连接已关闭。");

        } catch (IOException e) {
            System.out.println("IOException caught: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
